# knn.auk
# Tim Menzies
# Sept 12, 2012

@include "globals.awk"
@include "readcsv.awk"
@include "dist.awk"
@include "lib.awk"

function _knn(   o) {
  args("-seed,1,-k,1,-d,data/autompg.csv,--n,1,-pre, ,--echo,1",o)
  knn(o["-d"],o["-seed"],o["--n"],
      o["-k"],o["-pre"],o["-echo"])
}
function knn(f,seed,normp,k,pre,echo,   _Rows,gots,i,chops,s) {
  s= f":k="k",n="normp","pre
  print s
  if (echo) print s>"/dev/stderr"
  readcsv("cat " f,_Rows)
  kall(k,_Rows,normp,gots)
  for(i in gots) 
    print gots[i]  
}
function kall(k,_Rows,normp,gots,	  i) {
  for(i in all) 
    gots[i] = k1(k,all[i],_Rows,normp)
}
function  k1(k,row1,_Rows,normp,  \
                n,near,i,m,klass,got,want) {
  klass= klass1(gp)
  n = kth(k,row1,all,_Rows, normp,near)
  for(i in near)
    m += d[near[i]][klass]
  got  =  m/n
  want = d[row1][klass]
  return int(100*abs(want - got)/want)
}
